




const historyList = document.getElementById('historyList');
const totalRecords = document.getElementById('totalRecords');
const totalXunfei = document.getElementById('totalXunfei');
const totalQwen = document.getElementById('totalQwen');


let allHistory = [];


document.addEventListener('DOMContentLoaded', () => {
    console.log('📜 历史记录页面加载完成');
    loadHistory();
});




async function loadHistory() {
    try {
        const response = await fetch('/api/history?limit=100', {
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            allHistory = result.history;
            displayHistory(allHistory);
            calculateStats(allHistory);
        } else {
            throw new Error(result.error || '加载失败');
        }
    } catch (error) {
        console.error('❌ 加载历史记录失败:', error);
        historyList.innerHTML = `
            <p class="placeholder">加载失败: ${error.message}</p>
        `;
    }
}




function displayHistory(history) {
    if (history.length === 0) {
        historyList.innerHTML = '<p class="placeholder">暂无历史记录</p>';
        return;
    }

    historyList.innerHTML = history.map(record => `
        <div class="result-section" style="margin-bottom: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <div>
                    <span style="font-weight: 600; color: var(--french-blue);">
                        ${record.direction === 'zh2fr' ? '🇨🇳 中文 → 🇫🇷 法语' : '🇫🇷 法语 → 🇨🇳 中文'}
                    </span>
                    <span style="margin-left: 15px; color: #999; font-size: 13px;">
                        🕐 ${formatDate(record.created_at)}
                    </span>
                </div>
                <div style="font-size: 12px; color: #666;">
                    讯飞: ${record.xunfei_tokens} 字符 | 千问: ${record.qwen_tokens} tokens
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div>
                    <div style="font-weight: 600; color: #666; margin-bottom: 5px; font-size: 13px;">📝 原文</div>
                    <div style="padding: 12px; background: white; border-radius: 8px; font-size: 14px;">
                        ${escapeHtml(record.original_text)}
                    </div>
                </div>
                <div>
                    <div style="font-weight: 600; color: #666; margin-bottom: 5px; font-size: 13px;">✨ 翻译结果</div>
                    <div style="padding: 12px; background: white; border-radius: 8px; font-size: 14px;">
                        ${escapeHtml(record.polished_text || record.translated_text)}
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}




function calculateStats(history) {
    const total = history.length;
    const xunfei = history.reduce((sum, r) => sum + r.xunfei_tokens, 0);
    const qwen = history.reduce((sum, r) => sum + r.qwen_tokens, 0);

    totalRecords.textContent = total;
    totalXunfei.textContent = xunfei.toLocaleString();
    totalQwen.textContent = qwen.toLocaleString();
}




function formatDate(isoString) {
    const date = new Date(isoString);
    const now = new Date();
    const diff = now - date;

    if (diff < 3600000) {
        const minutes = Math.floor(diff / 60000);
        return minutes <= 1 ? '刚刚' : `${minutes}分钟前`;
    }

    if (diff < 86400000) {
        const hours = Math.floor(diff / 3600000);
        return `${hours}小时前`;
    }

    if (date.toDateString() === now.toDateString()) {
        return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }

    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }

    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
}




function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}




async function handleLogout() {
    if (!confirm('确定要登出吗？')) {
        return;
    }

    try {
        const response = await fetch('/api/auth/logout', {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            window.location.href = '/login';
        }
    } catch (error) {
        console.error('登出错误:', error);
        window.location.href = '/login';
    }
}

window.handleLogout = handleLogout;

